// index.js
Page({
  data: {
    tasks: [],
    showSignModal: false,
    currentTask: null,
    code: '',
    selectedPoints: [],
    gestureSequence: '',
    showScanAnimation: false,
    typeMap: {
      'NORMAL': '一键签到',
      'CODE': '签到码签到',
      'GESTURE': '手势签到',
      'QR_CODE': '二维码签到',
      'LOCATION': '位置签到'
    },
    statusMap: {
      0: '未签到',
      1: '已签到',
      2: '缺勤'
    }
  },

  onLoad() {
    this.loadTasks();
  },

  loadTasks() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }

    wx.showLoading({
      title: '加载中...'
    });

    wx.request({
      url: 'http://localhost:8080/api/student/attendance/tasks',
      method: 'GET',
      header: {
        'Authorization': token
      },
      success: (res) => {
        if (res.data.code === 1) {
          const tasks = res.data.data.sort((a, b) => {
            return new Date(b.startTime) - new Date(a.startTime);
          });
          this.setData({ tasks });
        } else {
          wx.showToast({
            title: res.data.msg || '获取签到列表失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取签到列表失败:', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 显示签到弹窗
  showSignModal(e) {
    const task = e.currentTarget.dataset.task;
    console.log('当前任务：', task); // 添加日志
    this.setData({
      showSignModal: true,
      currentTask: task,
      code: '',
      selectedPoints: [],
      gestureSequence: ''
    });
  },

  // 隐藏签到弹窗
  hideSignModal() {
    this.setData({
      showSignModal: false
    });
  },

  // 一键签到
  quickSign() {
    const { currentTask } = this.data;
    const token = wx.getStorageSync('token');
    
    wx.request({
      url: 'http://localhost:8080/api/student/attendance/quick',
      method: 'POST',
      header: {
        'Authorization': token
      },
      data: {
        taskId: currentTask.id
      },
      success: (res) => {
        if (res.data.code === 1) {
          wx.showToast({
            title: '签到成功',
            icon: 'success'
          });
          this.hideSignModal();
          this.loadTasks();
        } else {
          wx.showToast({
            title: res.data.msg || '签到失败',
            icon: 'none'
          });
        }
      }
    });
  },

  // 输入签到码
  onCodeInput(e) {
    this.setData({
      code: e.detail.value
    });
  },

  // 签到码签到
  codeSign() {
    const { currentTask, code } = this.data;
    if (!code) {
      wx.showToast({
        title: '请输入签到码',
        icon: 'none'
      });
      return;
    }

    const token = wx.getStorageSync('token');
    wx.request({
      url: 'http://localhost:8080/api/student/attendance/code',
      method: 'POST',
      header: {
        'Authorization': token
      },
      data: {
        taskId: currentTask.id,
        code: code
      },
      success: (res) => {
        if (res.data.code === 1) {
          wx.showToast({
            title: '签到成功',
            icon: 'success'
          });
          this.hideSignModal();
          this.loadTasks();
        } else {
          wx.showToast({
            title: res.data.msg || '签到失败',
            icon: 'none'
          });
        }
      }
    });
  },

  // 位置签到
  locationSign() {
    const { currentTask } = this.data;
    const token = wx.getStorageSync('token');

    // 检查是否有位置权限
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.userLocation']) {
          // 没有权限，引导用户开启
          wx.authorize({
            scope: 'scope.userLocation',
            success: () => {
              this.getLocationAndSign(currentTask, token);
            },
            fail: () => {
              // 用户拒绝授权，引导用户去设置页面开启
              wx.showModal({
                title: '需要位置权限',
                content: '请在设置中开启位置权限，以便进行签到',
                confirmText: '去设置',
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    wx.openSetting();
                  }
                }
              });
            }
          });
        } else {
          // 已有权限，直接获取位置
          this.getLocationAndSign(currentTask, token);
        }
      }
    });
  },

  // 获取位置并签到
  getLocationAndSign(task, token) {
    wx.showLoading({
      title: '获取位置中...'
    });

    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      highAccuracyExpireTime: 3000,
      success: (res) => {
        console.log('获取位置成功：', res);
        // 发送签到请求
        wx.request({
          url: 'http://localhost:8080/api/student/attendance/location',
          method: 'POST',
          header: {
            'Authorization': token
          },
          data: {
            taskId: task.id,
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: (res) => {
            if (res.data.code === 1) {
              wx.showToast({
                title: '签到成功',
                icon: 'success'
              });
              this.hideSignModal();
              this.loadTasks();
            } else {
              wx.showToast({
                title: res.data.msg || '签到失败',
                icon: 'none'
              });
            }
          },
          fail: (err) => {
            console.error('位置签到请求失败：', err);
            wx.showToast({
              title: '签到失败，请重试',
              icon: 'none'
            });
          }
        });
      },
      fail: (err) => {
        console.error('获取位置失败：', err);
        wx.showToast({
          title: '获取位置失败，请检查GPS是否开启',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 点击手势点
  onGesturePointTap(e) {
    const index = e.currentTarget.dataset.index;
    let { selectedPoints, gestureSequence } = this.data;
    
    if (!selectedPoints.includes(index)) {
      selectedPoints.push(index);
      gestureSequence += (index + 1).toString();
      
      this.setData({
        selectedPoints,
        gestureSequence
      });
    }
  },

  // 手势签到
  gestureSign() {
    const { currentTask, gestureSequence } = this.data;
    if (!gestureSequence) {
      wx.showToast({
        title: '请绘制手势',
        icon: 'none'
      });
      return;
    }

    const token = wx.getStorageSync('token');
    wx.request({
      url: 'http://localhost:8080/api/student/attendance/gesture',
      method: 'POST',
      header: {
        'Authorization': token
      },
      data: {
        taskId: currentTask.id,
        gestureSequence: gestureSequence
      },
      success: (res) => {
        if (res.data.code === 1) {
          wx.showToast({
            title: '签到成功',
            icon: 'success'
          });
          this.hideSignModal();
          this.loadTasks();
        } else {
          wx.showToast({
            title: res.data.msg || '签到失败',
            icon: 'none'
          });
        }
      }
    });
  },

  // 二维码签到
  scanQRCode() {
    const { currentTask } = this.data;
    const token = wx.getStorageSync('token');

    // 显示扫描动画
    this.setData({ showScanAnimation: true });

    wx.scanCode({
      scanType: ['qrCode'],
      success: (res) => {
        console.log('扫码结果：', res);
        // 尝试解析二维码内容
        let qrCode = '';
        try {
          // 二维码内容可能是 "taskId:qrCode" 格式
          const qrContent = res.result;
          const parts = qrContent.split(':');
          if (parts.length === 2) {
            qrCode = parts[1]; // 取第二部分作为 qrCode
          } else {
            // 如果不是预期格式，就直接使用扫描结果
            qrCode = qrContent;
          }

          wx.request({
            url: 'http://localhost:8080/api/student/attendance/qrcode',
            method: 'POST',
            header: {
              'Authorization': token
            },
            data: {
              taskId: currentTask.id,
              qrCode: qrCode
            },
            success: (res) => {
              if (res.data.code === 1) {
                wx.showToast({
                  title: '签到成功',
                  icon: 'success'
                });
                this.hideSignModal();
                this.loadTasks();
              } else {
                wx.showToast({
                  title: res.data.msg || '签到失败',
                  icon: 'none'
                });
              }
            },
            fail: (err) => {
              console.error('二维码签到请求失败：', err);
              wx.showToast({
                title: '签到失败，请重试',
                icon: 'none'
              });
            }
          });
        } catch (error) {
          console.error('解析二维码失败：', error);
          wx.showToast({
            title: '无效的二维码',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('扫码失败：', err);
        wx.showToast({
          title: '扫码失败，请重试',
          icon: 'none'
        });
      },
      complete: () => {
        // 隐藏扫描动画
        this.setData({ showScanAnimation: false });
      }
    });
  },

  navigateToAttendance() {
    wx.switchTab({
      url: '/pages/attendance/attendance'
    });
  }
});
